<template>
    <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
               :close-on-press-escape="false">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()"
                 :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'">
            <el-row :gutter="30">
                <el-col :span="24">
                    <el-form-item label="旅游路线名称" prop="name">
                        <el-input v-model="dataForm.name" placeholder="旅游路线名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="导览图" prop="mapGuideId">
                        <el-select v-model="dataForm.mapGuideId" placeholder="请选择导览图">
                            <el-option
                                    v-for="item in datadaolantuList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="简介" prop="intro">
                        <el-input v-model="dataForm.intro" placeholder="简介"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="标签类型" prop="tagsId">
                        <el-select v-model="dataForm.tagsIdArr" placeholder="标签类型" multiple>
                            <el-option v-for="item, index in tagOptions" :key="index" :label="item.name"
                                       :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="图片(最多10张)" prop="">
                        <el-upload :action="url" :file-list="fileList" :limit="10" :before-upload="beforeUploadHandle"
                                   list-type="picture-card" :on-success="successHandle" :on-remove="handleRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item :label="`${'第' + (index + 1) + '天'}`" v-for="(items, index) in dataForm.scheduleList"
                                  :key="index" :prop="'scheduleList.' + index + '.scenicSpotIdArr'" :rules="{
                            required: true, message: '请输入', trigger: 'blur'
                        }">
                        <el-select value-key="id" v-model="items.scenicSpotIdArr" placeholder="请选择名称" multiple>
                            <el-option v-for="(item, index) in SpotList" :key="index" :label="item.name"
                                       :value="item.id"></el-option>
                        </el-select>
                        <el-button type="danger" size="mini" @click="deleteDays(index)"
                                   style="margin-left:15px">删除天数</el-button>
                        <el-button type="primary" size="mini" v-if="index == dataForm.scheduleList.length - 1"
                                   @click="addDays()">添加天数</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item>
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- <el-color-picker v-model="domain.tagsColor">
            </el-color-picker> -->
            <!-- <el-form-item label="行程天数" prop="planDayNum">
        <el-input v-model="dataForm.planDayNum" placeholder="计划旅游天数"></el-input>
      </el-form-item>
      <el-form-item label="景点数" prop="planPlaceNum">
        <el-input v-model="dataForm.planPlaceNum" placeholder="计划游玩地点数"></el-input>
      </el-form-item> -->
            <!-- <el-form-item label="创建人" prop="creator">
        <el-input v-model="dataForm.creator" placeholder="创建人"></el-input>
      </el-form-item>
      <el-form-item label="创建时间" prop="createDate">
        <el-input v-model="dataForm.createDate" placeholder="创建时间"></el-input>
      </el-form-item>
      <el-form-item label="修改人" prop="updater">
        <el-input v-model="dataForm.updater" placeholder="修改人"></el-input>
      </el-form-item>
      <el-form-item label="修改时间" prop="updateDate">
        <el-input v-model="dataForm.updateDate" placeholder="修改时间"></el-input>
      </el-form-item> -->
        </el-form>
        <template slot="footer">
            <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
            <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
        </template>
    </el-dialog>
</template>

<script>
    import Cookies from "js-cookie";
    import debounce from 'lodash/debounce'
    export default {
        data() {
            return {
                datadaolantuList:[],
                scheduleList: [
                    { scenicSpotIdArr: [] }
                ],
                visible: false,
                tagOptions: [],
                url: `${window.SITE_CONFIG["apiURL"]
                    }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
                // url: `https://i.ringzle.com/island-cloud-server/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
                fileList: [],
                dataForm: {
                    id: '',
                    mapGuideId:'',
                    name: '',
                    intro: '',
                    planDayNum: '',
                    planPlaceNum: '',
                    status: '',
                    coverImageList: [],
                    tagsIdArr: [],
                    scheduleList: [{
                        //scenicSpotIdArr: [], //景点idArr
                        scenicSpotIdArr: [],
                        typeArr: []
                    }],
                },
                SpotList: []
            }
        },
        mounted() {
            this.getTagsList();
            this.getScenicSpot()
            this.getdaolantudata();
        },
        watch: {
            'dataForm.scheduleList': {
                deep: true,
                handler(newV) { }
            }
        },
        computed: {
            dataRule() {
                return {
                    name: [{
                        required: true,
                        message: this.$t('validate.required'),
                        trigger: 'blur'
                    }],
                    intro: [{
                        required: true,
                        message: this.$t('validate.required'),
                        trigger: 'blur'
                    }],
                    planDayNum: [{
                        required: true,
                        message: this.$t('validate.required'),
                        trigger: 'blur'
                    }],
                    planPlaceNum: [{
                        required: true,
                        message: this.$t('validate.required'),
                        trigger: 'blur'
                    }],
                    creator: [{
                        required: true,
                        message: this.$t('validate.required'),
                        trigger: 'blur'
                    }],
                    createDate: [{
                        required: true,
                        message: this.$t('validate.required'),
                        trigger: 'blur'
                    }],
                    updater: [{
                        required: true,
                        message: this.$t('validate.required'),
                        trigger: 'blur'
                    }],
                    updateDate: [{
                        required: true,
                        message: this.$t('validate.required'),
                        trigger: 'blur'
                    }]
                }
            }
        },
        methods: {
            getdaolantudata() {
                this.$http
                    .get("/sys/ismapguide/page", {
                        params: {
                            name: '',
                            page: 1,
                            limit: 99999,
                            active: '',
                        }
                    })
                    .then((res) => {
                        //  console.log('111111111111111111',res)
                        if (res.data.code == 0) {
                            this.datadaolantuList = res.data.data.list;

                        } else {
                            this.$message.error(res.data.msg);
                        }
                    });
            },
            changeSpot(e, index) {
                // this.dataForm.scheduleList
                console.log(e, index, '++++++++++');
                let idArr = []
                let TypeArr = []
                e.forEach((item, index) => {
                    let [id, type] = item.split(',')
                    idArr.push(id)
                    TypeArr.push(type)
                });
                this.scheduleList[index].scenicSpotIdArr = idArr
                this.scheduleList[index].typeArr = TypeArr
                console.log(this.scheduleList[index], '***********');

            },
            handleRemove(file, fileList) {

                this.dataForm.coverImageList = fileList.map((item) => {
                    return item.url;
                });
                const removeIndex = this.fileList.findIndex(i => i.url == file.url)
                this.fileList.splice(removeIndex, 1)
            },
            // 上传之前
            beforeUploadHandle(file) {
                if (
                    file.type !== "image/jpg" &&
                    file.type !== "image/jpeg" &&
                    file.type !== "image/png" &&
                    file.type !== "image/gif"
                ) {
                    this.$message.error(this.$t("upload.tip", {
                        format: "jpg、png、gif"
                    }));
                    return false;
                }
            },
            // 上传成功
            successHandle(res, file, fileList) {

                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                this.fileList.unshift({
                    name: "",
                    url: res.data.url,
                });
                this.dataForm.coverImageList = this.fileList.map((item) => {
                    return item.url;
                });
            },
            //获取标签
            getTagsList() {
                this.$http.post('/scenic/customtags/selectList').then(({
                                                                           data: res
                                                                       }) => {
                    if (res.msg == 'success') {
                        this.tagOptions = res.data
                    }
                })
            },
            //获取景点list
            getScenicSpot() {
                this.$http.post('/sys/ismap/selectAllCusSpot ').then(res => {
                    if (res.data.code == 0) {
                        this.SpotList = res.data.data;
                    }
                })
            },
            deleteDays(index) {
                this.dataForm.scheduleList.splice(index, 1)
            },
            addDays() {
                this.dataForm.scheduleList.push({
                    scenicSpotIdArr: [],
                    typeArr: []
                })
            },
            init() {
                this.visible = true
                this.$nextTick(() => {
                    this.fileList = [];
                    this.$refs['dataForm'].resetFields()
                    if (this.dataForm.id) {
                        this.getInfo()
                        return
                    }
                    this.scheduleList = [
                        { scenicSpotIdArr: [] }
                    ]
                    this.dataForm = {
                        id: '',
                        name: '',
                        mapGuideId:'',
                        intro: '',
                        planDayNum: '',
                        planPlaceNum: '',
                        coverImageList: [],
                        tagsIdArr: [],
                        scheduleList: [{
                            scenicSpotIdArr: []
                        }],

                    }
                })
            },
            // 获取信息
            getInfo() {
                this.$http.get(`/scenic/recroute/queryRecRouteDetail/${this.dataForm.id}`).then(({
                                                                                                     data: res
                                                                                                 }) => {
                    this.fileList = [];
                    if (res.code !== 0) {
                        return this.$message.error(res.msg)
                    }
                    this.dataForm = {
                        ...this.dataForm,
                        ...res.data
                    }
                    this.scheduleList = this.dataForm.scheduleList
                    this.dataForm.coverImageList.filter((item) => {
                        this.fileList.push({
                            url: item
                        })
                    })
                }).catch(() => { })
            },
            // 表单提交
            dataFormSubmitHandle: debounce(function () {
                this.$refs['dataForm'].validate((valid) => {
                    if (!valid) {
                        return false
                    }
                    this.dataForm.scheduleList.forEach((item, index) => {
                        this.dataForm.scheduleList[index].typeArr = []
                        item.scenicSpotIdArr.forEach((i) => {
                            this.SpotList.forEach(e => {
                                if (e.id == i) {
                                    this.dataForm.scheduleList[index].typeArr.push(e.type)
                                }
                            })
                        })
                    })
                    console.log(this.dataForm.scheduleList, '++++');
                    this.$http[!this.dataForm.id ? 'post' : 'put']('/scenic/recroute/', this.dataForm).then(({
                                                                                                                 data: res
                                                                                                             }) => {
                        if (res.code !== 0) {
                            return this.$message.error(res.msg)
                        }
                        this.$message({
                            message: this.$t('prompt.success'),
                            type: 'success',
                            duration: 500,
                            onClose: () => {
                                this.visible = false
                                this.$emit('refreshDataList')
                            }
                        })
                    }).catch(() => { })
                })
            }, 1000, {
                'leading': true,
                'trailing': false
            })
        }
    }
</script>

<style scoped lang="scss">
    .avatar-uploader {
        .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;

            .el-upload:hover {
                border-color: #409eff;
            }
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 158px;
            height: 158px;
            line-height: 158px;
            text-align: center;
        }

        .avatar {
            width: 158px;
            height: 158px;
            display: block;
        }
    }
</style>
